//
//  BBScrollImageView.m
//  ImageScrollView
//
//  Created by box on 13-12-17.
//  Copyright (c) 2013年 box. All rights reserved.
//
/*!示例代码
 
 
 NSArray *iamgeArr = @[@"http://a.hiphotos.baidu.com/image/w%3D2048/sign=32935a25e9c4b7453494b016fbc41f17/1c950a7b02087bf432178be5f0d3572c10dfcfc7.jpg",
 @"http://img10.itiexue.net/1774/17747038.jpg?19",
 @"http://img1.itiexue.net/1774/17747245.jpg?58",
 @"http://img3.itiexue.net/1774/17747247.jpg?58",
 @"http://img4.itiexue.net/1774/17747248.jpg?58",
 @"http://img6.itiexue.net/1774/17747250.jpg?58",
 @"http://img8.itiexue.net/1774/17747252.jpg?58",
 @"http://img0.itiexue.net/1774/17740392.jpg?30",
 @"http://img2.itiexue.net/1774/17740310.jpg?59",
 @"http://img1.itiexue.net/1773/17730157.jpg?26",
 @"http://img8.itiexue.net/1773/17730164.jpg?26",];
 urls = [[NSMutableArray alloc]init];
 for (NSString *str in iamgeArr) {
 [urls addObject:[NSURL URLWithString:str]];
 }
 
 
 
 
 scrollImageView = [BBScrollImageView scrollImageViewWithFrame:CGRectMake(10, 70, 300, 120)];
 scrollImageView.delegate = self;
 scrollImageView.dataSource = self;
 scrollImageView.autoPlay = YES;
 scrollImageView.showFullImageWhenClick = NO;
 scrollImageView.pageControlLimit = 100;
 scrollImageView.titleContentView.backgroundColor = [UIColor clearColor];
 [scrollImageView.pageControl setAlignment:kBBIndicatorAlignmentCenter];
 [self.view addSubview:scrollImageView];
 
 */
#import "SDImageCache.h"
#import "BBScrollImageView.h"
#import "BBLargeImageView.h"
#import "UIImageView+WebCache.h"



#define nexturlIndex (_urls.count==_urlIndex+1?0:_urlIndex+1)
#define lasturlIndex (0==_urlIndex?_urls.count-1:_urlIndex-1)

#define nextImageViewIndex (_imageViewArr.count==imageViewIndex+1?0:imageViewIndex+1)
#define lastImageViewIndex (0==imageViewIndex?_imageViewArr.count-1:imageViewIndex-1)

#define curCenter CGPointMake(self.center.x-self.frame.origin.x, self.center.y-self.frame.origin.y)
#define nextCenter CGPointMake(self.center.x-self.frame.origin.x+self.frame.size.width, self.center.y-self.frame.origin.y)
#define lastCenter CGPointMake(self.center.x-self.frame.origin.x-self.frame.size.width, self.center.y-self.frame.origin.y)

//方向
typedef NS_ENUM(NSUInteger, Direction) {
    DirectionNone = 0, //无
    DirectionLeft, //向左
    DirectionRight //向右
};

@interface BBScrollImageView()<UIImageViewWebCacheDelegate,BBLargeImageViewDelegate,BBLargeImageViewDataSource,SDWebImageDownloaderDelegate,UIScrollViewDelegate>
{
    NSInteger imageViewIndex;//当前显示imageView的索引
    NSTimer *_timer;
    Direction lastOffsetDirection;//上一次scrollView的偏移方向（pageEnable，一共三页，如果在第一页就是left，第三页就是right）
}

@property (retain, nonatomic) IBOutlet UILabel *numberLbl;
@property (retain, nonatomic) NSArray *imageViewArr;
@property (retain, nonatomic) IBOutlet UIScrollView *scrollView;
@property (assign,nonatomic)NSMutableArray *urls;
@property (assign,nonatomic)NSMutableArray *titles;//标题
@property (assign,nonatomic)Direction currentDirection;//当前滚动的方向


@end


@implementation BBScrollImageView

- (void)dealloc {
    [self stopTimer];
    [_titleContentView release];
    [_titleLbl release];
    [_urls release];
    [_titles release];
    [_imageViewArr release];
    [_numberLbl release];
    [_pageControl release];
    [super dealloc];
}



- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        _autoPlay = NO;
        _showFullImageWhenClick = NO;
        _showIndicator = YES;
        _autoPlayDuration = 3.0f;
        _animateDuration = 0.8f;
        _pageControlLimit = 5;
        _timer = nil;
        _urls = [[NSMutableArray alloc]init];
        _titles = [[NSMutableArray alloc]init];
        _imageViewArr = [[NSArray alloc]initWithObjects:[self viewWithTag:1000],[self viewWithTag:1001], nil];
        
        [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.1];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [super drawRect:rect];
    //    [[SDImageCache sharedImageCache]clearDisk];
    //    [[SDImageCache sharedImageCache]cleanDisk];
}


- (void)removeFromSuperview
{
    _delegate = nil;
    _dataSource = nil;
    [self stopTimer];
    [super removeFromSuperview];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
}

/*!
 *@description  初始化各种设置
 *@function     initSettings
 *@param        (void)
 *@return       (void)
 */
- (void)initSettings
{
    _pageControl = [[BBPageControl alloc] initWithFrame:CGRectMake(0, self.frame.size.height-20, self.frame.size.width, 10)];
    
    _pageControl.numberOfPages = 0;
    _pageControl.currentPage = 0;
    _pageControl.selectedColor = [UIColor orangeColor];
    _pageControl.otherColor = [UIColor whiteColor];
    _pageControl.alignment = kBBIndicatorAlignmentRight;
    _pageControl.hidden = YES;
    //    _pageControl.delegate = self;
    _pageControl.backgroundColor = [UIColor clearColor];
    _pageControl.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self addSubview:_pageControl];
    
    CGRect frame = _scrollView.frame;
    frame.size.width *= 3;
    _scrollView.contentSize = frame.size;
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
    _scrollView.delegate = self;
    
    //    UISwipeGestureRecognizer *left = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(onSkipToNextImage:)];
    //    left.direction = UISwipeGestureRecognizerDirectionLeft;
    //    [self addGestureRecognizer:left];
    //    [left release];
    //
    //
    //    UISwipeGestureRecognizer *right = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(onSkipToLastImage:)];
    //    right.direction = UISwipeGestureRecognizerDirectionRight;
    //    [self addGestureRecognizer:right];
    //    [right release];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onSelectImageView:)];
    [self addGestureRecognizer:tap];
    [tap release];
    
    
    for (UIImageView *imgView in _imageViewArr) {
        imgView.delegateCache = self;
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}
/*!
 *@description  载入url
 *@function     loadWithUrls
 *@param        urlArr  --url数组
 *@return       (void)
 */
- (void)loadWithUrls:(NSArray *)urlArr
{
    _urlIndex = 0;
    imageViewIndex = 0;
    
    for (UIImageView *imgView in _imageViewArr) {
        [[SDWebImageManager sharedManager]cancelForDelegate:imgView];
        if (imgView.tag==1000) {
            imgView.superview.center = curCenter;
            _visibleImageView = imgView;
        }else{
            imgView.superview.center = nextCenter;
        }
    }
    
    
    if (_showIndicator) {
        if (_urls.count > _pageControlLimit) {
            _pageControl.hidden = YES;
            _numberLbl.hidden = NO;
            _numberLbl.text = [NSString stringWithFormat:@"1/%d",_urls.count];
        }else{
            _pageControl.hidden = NO;
            _numberLbl.hidden = YES;
            _pageControl.numberOfPages = _urls.count;
            _pageControl.currentPage = 0;
        }
    }else{
        _pageControl.hidden = YES;
        _numberLbl.hidden = YES;
    }
    
    
    UIImageView *imageView = (UIImageView *)_imageViewArr[0];
    if (_urls.count) {
        [isLogin setVendorImageUrl:imageView :_urls[0]];
        // [imageView setImageWithURL:_urls[0]];
    }else{
        imageView.image = nil;
        [self imageView:imageView didSetWithImage:nil];
    }
    if (_titles.count) {
        _titleLbl.text = _titles[0];
    }
    
    [self resetTimer];
}

- (void)resetTimer
{
    [self stopTimer];
    if (_autoPlay && _urls.count>1) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_autoPlayDuration target:self selector:@selector(onAutoPlay:) userInfo:nil repeats:YES];
    }
}

- (void)stopTimer
{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)reloadData
{
    _titleLbl.hidden = YES;
    if (_dataSource && [_dataSource respondsToSelector:@selector(numberOfImagesInScrollImageView:)]) {
        
        [_urls removeAllObjects];
        
        _count = [_dataSource numberOfImagesInScrollImageView:self];
        
        if ([_dataSource respondsToSelector:@selector(scrollImageView:titleAtIndex:)]) {
            
            for (int i=0; i<_count; i++) {
                [_titles addObject:[_dataSource scrollImageView:self titleAtIndex:i]];
            }
            _titleLbl.hidden = NO;
        }
        
        if ([_dataSource respondsToSelector:@selector(scrollImageView:imageUrlAtIndex:)]) {
            
            
            for (int i=0; i<_count; i++) {
                [_urls addObject:[_dataSource scrollImageView:self imageUrlAtIndex:i]];
            }
            
            [self loadWithUrls:_urls];
        }
    }
}

/*!
 *@description  跳到下一张图片
 *@function     onSkipToNextImage:
 *@param        gesture     --手势
 *@return       (void)
 */
- (void)onSkipToNextImage:(UISwipeGestureRecognizer *)gesture
{
    if (_urls.count < 2) {
        return;
    }
    
    UIImageView *imageView = (UIImageView *)_imageViewArr[imageViewIndex];
    
    imageViewIndex = nextImageViewIndex;
    
    _urlIndex = nexturlIndex;
    UIImageView *nextImageView = (UIImageView *)_imageViewArr[imageViewIndex];
    //    self.userInteractionEnabled = NO;
    [nextImageView setImageWithURL:_urls[_urlIndex]];
    if (_titles.count) {
        _titleLbl.text = _titles[_urlIndex];
        [self randomAnimationForTitleLbl];
    }
    
    nextImageView.superview.center = nextCenter;
    
    _numberLbl.text = [NSString stringWithFormat:@"%d/%d",_urlIndex+1,_urls.count];
    _pageControl.currentPage = _urlIndex;
    
    
    if (gesture) {
        [self resetTimer];
    }
    [UIView animateWithDuration:_animateDuration animations:^{
        nextImageView.superview.center = curCenter;
        imageView.superview.center = lastCenter;
    } completion:^(BOOL finished) {
        _visibleImageView = nextImageView;
        [[SDWebImageManager sharedManager]cancelForDelegate:imageView];
        if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:didScrollToIndex:)]) {
            [_delegate scrollImageView:self didScrollToIndex:_urlIndex];
        }
    }];
}

/*!
 *@description  给外部调用的跳到下一张图
 *@function     skipToNextImage
 *@param        (void)
 *@return       (BOOL)  --跳转成功与否 不成功代表已经是最后一张了
 */
- (BOOL)skipToNextImage
{
    if (_urlIndex == _urls.count-1) {
        return NO;
    }
    
    [self onSkipToNextImage:nil];
    return YES;
}

/*!
 *@description  跳到上一张图片
 *@function     onSkipToLastImage:
 *@param        gesture     --手势
 *@return       (void)
 */
- (void)onSkipToLastImage:(UISwipeGestureRecognizer *)gesture
{
    if (_urls.count < 2) {
        return;
    }
    
    UIImageView *imageView = (UIImageView *)_imageViewArr[imageViewIndex];
    
    imageViewIndex = lastImageViewIndex;
    _urlIndex = lasturlIndex;
    UIImageView *lastImageView = (UIImageView *)_imageViewArr[imageViewIndex];
    //    self.userInteractionEnabled = NO;
    [lastImageView setImageWithURL:_urls[_urlIndex]];
    if (_titles.count) {
        _titleLbl.text = _titles[_urlIndex];
        [self randomAnimationForTitleLbl];
    }
    
    lastImageView.superview.center = lastCenter;
    
    _numberLbl.text = [NSString stringWithFormat:@"%d/%d",_urlIndex+1,_urls.count];
    _pageControl.currentPage = _urlIndex;
    
    if (gesture) {
        [self resetTimer];
    }
    [UIView animateWithDuration:_animateDuration animations:^{
        lastImageView.superview.center = curCenter;
        imageView.superview.center = nextCenter;
    } completion:^(BOOL finished) {
        _visibleImageView = lastImageView;
        [[SDWebImageManager sharedManager]cancelForDelegate:imageView];
        if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:didScrollToIndex:)]) {
            [_delegate scrollImageView:self didScrollToIndex:_urlIndex];
        }
    }];
}

- (void)randomAnimationForTitleLbl
{
    CATransition *anim = [CATransition animation];
    anim.removedOnCompletion = YES;
    anim.duration = _animateDuration;
    
    anim.type = kCATransitionMoveIn;
    anim.subtype = kCATransitionFromRight;
    NSArray *nameArr = @[kCAMediaTimingFunctionLinear,kCAMediaTimingFunctionEaseIn,kCAMediaTimingFunctionEaseOut,kCAMediaTimingFunctionEaseInEaseOut,kCAMediaTimingFunctionDefault];
    anim.timingFunction = [CAMediaTimingFunction functionWithName:nameArr[arc4random()%nameArr.count]];
    [_titleLbl.layer addAnimation:anim forKey:nil];
    
}

/*!
 *@description  给外部调用的跳到上一张图
 *@function     skipToNextImage
 *@param        (void)
 *@return       (BOOL)  --跳转成功与否 不成功代表已经是第一张了
 */
- (BOOL)skipToLastImage
{
    if (_urlIndex == 0) {
        return NO;
    }
    
    [self onSkipToLastImage:nil];
    return YES;
}

/*!
 *@description  响应点击图片
 *@function     onSelectImageView:
 *@param        gesture     --手势
 *@return       (void)
 */
- (void)onSelectImageView:(UITapGestureRecognizer *)gesture
{
    if (_showFullImageWhenClick) {
        UIWindow *window = [[[UIApplication sharedApplication]delegate]window];
        BBLargeImageView *largeView = [BBLargeImageView largeImageView];
        [largeView setCurIndex:_urlIndex after:0.1 animated:NO];
        largeView.dataSource = self;
        largeView.delegate = self;
        largeView.autoAnimate = YES;
        largeView.removeOnGoBack = YES;
        largeView.removeOnTouchImage = YES;
        largeView.adjustFrameToSuperView = YES;
        [window addSubview:largeView];
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:didSeletedImageView:atIndex:)]) {
        
        [_delegate scrollImageView:self didSeletedImageView:_imageViewArr[imageViewIndex] atIndex:_urlIndex];
    }
}

/*!
 *@description  自动播放
 *@function     onAutoPlay
 *@param        (void)
 *@return       (void)
 */
- (void)onAutoPlay:(NSTimer *)timer
{
    [self onSkipToNextImage:nil];
}
/*!
 *@description  获取在指定index的image，获取出来的图片在代理方法
 * - (void)scrollImageView:(BBScrollImageView *)aScrollImageView didGetImage:(UIImage *)aImage atIndex:(NSInteger)aIndex;
 * 中取
 *@function     getImageAtIndex
 *@param        aIndex  --图片的位置
 *@return       (void)
 */
- (void)getImageAtIndex:(NSInteger)aIndex
{
    if (aIndex >= _urls.count) {
        
        if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:failedToGetImageAtIndex:)]) {
            [_delegate scrollImageView:self failedToGetImageAtIndex:aIndex];
        }
        return;
    }
    
    [SDWebImageDownloader downloaderWithURL:_urls[aIndex] delegate:self userInfo:@(aIndex)];
}


- (Direction)currentDirection
{
    if (_scrollView.contentOffset.x > _scrollView.frame.size.width) {
        return DirectionRight;
    }else if (_scrollView.contentOffset.x < _scrollView.frame.size.width){
        return DirectionLeft;
    }else{
        return DirectionNone;
    }
}


+ (instancetype)scrollImageViewWithFrame:(CGRect)frame
{
    BBScrollImageView *scrollImageView = [[[NSBundle mainBundle]loadNibNamed:@"BBScrollImageView" owner:nil options:nil]lastObject];
    scrollImageView.frame = frame;
    [scrollImageView initSettings];
    return scrollImageView;
}

#pragma mark -
#pragma mark UIImageViewWebCacheDelegate method
//- (void)imageView:(UIImageView *)imageView didSetWithImage:(UIImage *)image
//{
//    UIView *indicatorView = [imageView.superview viewWithTag:imageView.tag+100];
//    [UIView animateWithDuration:1.0f animations:^{
//        indicatorView.alpha = 0.0f;
//    }completion:^(BOOL finished) {
//        // self.userInteractionEnabled = YES;
//        // indicatorView.hidden = YES;
//    }];
//}


#pragma mark -
#pragma mark BBLargeImageViewDataSource method
- (NSInteger)numberOfImagesInLargeImageView:(BBLargeImageView *)aLargeImageView
{
    return _urls.count;
}

- (NSURL *)largeImageView:(BBLargeImageView *)aLargeImageView urlForImageAtIndex:(NSInteger)aIndex
{
    return _urls[aIndex];
}


#pragma mark -
#pragma mark SDWebImageDownloaderDelegate method

- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithImage:(UIImage *)image
{
    //    if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:didGetImage:atIndex:)]) {
    //        [_delegate scrollImageView:self didGetImage:image atIndex:[downloader.userInfo integerValue]];
    //    }
}

- (void)imageDownloader:(SDWebImageDownloader *)downloader didFailWithError:(NSError *)error
{
    //    if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:failedToGetImageAtIndex:)]) {
    //        [_delegate scrollImageView:self failedToGetImageAtIndex:[downloader.userInfo integerValue]];
    //    }
}


#pragma mark -
#pragma mark UIScrollViewDelegate method

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_urls.count < 2) {
        return;
    }
    
    if (self.currentDirection != lastOffsetDirection) {
        lastOffsetDirection = self.currentDirection;
        if (lastOffsetDirection == DirectionRight) {
            
            NSInteger nextIndex = nextImageViewIndex;
            UIImageView *nextImageView = (UIImageView *)_imageViewArr[nextIndex];

            NSInteger urlIndex = nexturlIndex;
            [nextImageView setImageWithURL:_urls[urlIndex]];
            nextImageView.superview.center = nextCenter;
        }else{
            NSInteger lastIndex = lastImageViewIndex;
            UIImageView *lastImageView = (UIImageView *)_imageViewArr[lastIndex];
            NSInteger urlIndex = lastIndex;
            
            [lastImageView setImageWithURL:_urls[urlIndex]];
            lastImageView.superview.center = lastCenter;
        }
    }
    
    CGFloat offset = _scrollView.contentOffset.x - _scrollView.frame.size.width;
    if (lastOffsetDirection == DirectionRight) {
        
        UIImageView *imageView = (UIImageView *)_imageViewArr[imageViewIndex];
        NSInteger nextIndex = nextImageViewIndex;
        UIImageView *nextImageView = (UIImageView *)_imageViewArr[nextIndex];
        imageView.superview.center = CGPointMake(curCenter.x-offset
                                                 , imageView.superview.center.y);
        nextImageView.superview.center = CGPointMake(nextCenter.x-offset
                                                     , nextImageView.superview.center.y);
    }else{
        UIImageView *imageView = (UIImageView *)_imageViewArr[imageViewIndex];
        NSInteger lastIndex = nextImageViewIndex;
        UIImageView *lastImageView = (UIImageView *)_imageViewArr[lastIndex];
        imageView.superview.center = CGPointMake(curCenter.x-offset
                                                 , imageView.superview.center.y);
        lastImageView.superview.center = CGPointMake(lastCenter.x-offset
                                                     , lastImageView.superview.center.y);
        
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    Direction curDirection = self.currentDirection;
    
    if (curDirection != DirectionNone) {
        
        if (curDirection == DirectionRight) {
            _urlIndex = nexturlIndex;
            imageViewIndex = nextImageViewIndex;
        }else if (curDirection == DirectionLeft){
            _urlIndex = lasturlIndex;
            imageViewIndex = lastImageViewIndex;
        }
        
        UIImageView *imageView = (UIImageView *)_imageViewArr[imageViewIndex];
        _visibleImageView = imageView;
        if (_titles.count) {
            _titleLbl.text = _titles[_urlIndex];
        }
        _numberLbl.text = [NSString stringWithFormat:@"%d/%d",_urlIndex+1,_urls.count];
        _pageControl.currentPage = _urlIndex;
        
        
        [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
        
        
        [[SDWebImageManager sharedManager]cancelForDelegate:imageView];
        if (_delegate && [_delegate respondsToSelector:@selector(scrollImageView:didScrollToIndex:)]) {
            [_delegate scrollImageView:self didScrollToIndex:_urlIndex];
        }
    }
    
    [self resetTimer];
    
}

@end
